/**
 *
 */
package com.bn.feeds.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.regex.Pattern;

import org.apache.commons.io.FilenameUtils;

import atg.core.util.StringUtils;
import atg.nucleus.GenericService;

/**
 * The Class FileUtils.
 */
public class FeedFileUtils extends GenericService {

    /**
     * Gets a file with given prefix from a given location
     *
     * @param filePath
     *            the file path
     * @param prefix
     *            the prefix
     * @return the file
     */
    public File getFile(String filePath, String prefix) {

        File folder = new File(filePath);
        FilenameFilter filter = new FileNameFilterImpl(prefix + '_');
        File[] listOfFiles = folder.listFiles(filter);
        if (listOfFiles == null || listOfFiles.length == 0) {
            return null;
        }
        return listOfFiles[0];
    }

    public File[] getFile(String filePath) {

        File folder = new File(filePath);
        return folder.listFiles();
    }

    /**
     * Gets a controlFile
     */
    public File fetchControlFile(String filePath, String fileName, String fileExtension) {
        File controlFile = new File((filePath).concat(fileName).concat(fileExtension));
        return controlFile;
    }

    /**
     * Archive a given file to the location specified.
     *
     * @param newfilePath
     *            the newfile path
     * @param fileObject
     *            the file object
     * @return the file
     */
    public void archiveFile(final String directoryPath, final File originalFile) {
        if (!StringUtils.isBlank(directoryPath) && originalFile != null) {
            File file = new File(directoryPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String path = directoryPath;
            if (!directoryPath.endsWith("\\") && !directoryPath.endsWith("/")) {
                path += File.separatorChar;
            }
            path += originalFile.getName();
            originalFile.renameTo(new File(path));
        }
    }

    /**
     * Move to archive.
     *
     * @param directoryPath
     *            the directory path
     * @param originalFile
     *            the original file
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    public void moveToArchive(final String directoryPath, final File originalFile) {
        String destinationFilePath = null;
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMddyyhhmmss");
        if (originalFile != null) {
            destinationFilePath = directoryPath + File.separator + "archives" + File.separator;
            final File file = new File(destinationFilePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            destinationFilePath += simpleDateFormat.format(Calendar.getInstance().getTime()) + "_" + originalFile.getName();
            originalFile.renameTo(new File(destinationFilePath));
        }
    }

    /**
     * Write error log to file.
     *
     * @param errorItemList
     *            the error item list
     * @param errorDirectoryPath
     *            the error directory path
     * @param feedFileName
     *            the feed file name
     * @param postFix
     *            the post fix
     */
    public void writeErrorLogToFile(StringBuilder errorItemList, File errorFile) {
        if (errorItemList != null && errorItemList.length() > 0) {
            if (errorFile != null) {
                BufferedWriter bw = null;
                try {
                    if (!errorFile.exists()) {
                        errorFile.createNewFile();
                    }
                    if (errorFile.canWrite()) {
                        FileWriter fw = new FileWriter(errorFile.getAbsoluteFile());
                        bw = new BufferedWriter(fw);
                        bw.write(Pattern.compile("<br />").matcher(errorItemList).replaceAll("\n"));
                    }
                } catch (IOException e) {
                    if (isLoggingError()) {
                        logError("Can not write to File : " + errorFile.getAbsolutePath(), e);
                    }
                } finally {
                    try {
                        if (bw != null) {
                            bw.close();
                        }
                    } catch (IOException e) {
                        if (isLoggingError()) {
                            logError("Can not BufferredWriter: " + errorFile.getAbsolutePath(), e);
                        }
                    }
                }
            } else {
                if (isLoggingDebug()) {
                    logDebug("file Object is null");
                }
            }
        } else {
            if (isLoggingDebug()) {
                logDebug("The data propvided to be written is Empty");
            }
        }
    }

    /**
     * Write error log to file.
     *
     * @param errorItemList
     *            the error item list
     * @param errorDirectoryPath
     *            the error directory path
     * @param feedFileName
     *            the feed file name
     * @param postFix
     *            the post fix
     */
    public void writeErrorLogToFile(StringBuilder errorItemList, String errorDirectoryPath, String feedFileName, String postFix) {
        if (errorItemList != null && errorItemList.length() > 0) {
            if (!StringUtils.isEmpty(errorDirectoryPath)) {
                if (!StringUtils.isEmpty(feedFileName)) {
                    feedFileName = FilenameUtils.removeExtension(feedFileName);
                    StringBuilder fileName = new StringBuilder();
                    fileName.append(feedFileName).append(postFix).append(".log");
                    File errorFile = new File(errorDirectoryPath, fileName.toString());
                    BufferedWriter bw = null;
                    try {
                        if (!errorFile.exists()) {
                            errorFile.createNewFile();
                        }
                        if (errorFile.canWrite()) {
                            FileWriter fw = new FileWriter(errorFile.getAbsoluteFile());
                            bw = new BufferedWriter(fw);
                            bw.write(Pattern.compile("<br />").matcher(errorItemList).replaceAll("\n"));
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        // e.printStackTrace();
                    } finally {
                        try {
                            if (bw != null) {
                                bw.close();
                            }
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            // e.printStackTrace();
                        }
                    }
                }
            } else {
                if (isLoggingDebug()) {
                    logDebug("file path is null");
                }
            }
        } else {
            if (isLoggingDebug()) {
                logDebug("The data propvided to be written is Empty");
            }
        }
    }

    public File getErrorLogFile(String errorDirectoryPath, String feedFileName, String postFix) {
        File errorFile = null;

        if (!StringUtils.isEmpty(errorDirectoryPath)) {
            if (!StringUtils.isEmpty(feedFileName)) {
                feedFileName = FilenameUtils.removeExtension(feedFileName);
                StringBuilder fileName = new StringBuilder();
                fileName.append(feedFileName).append(postFix).append(".log");
                errorFile = new File(errorDirectoryPath, fileName.toString());

                if (!errorFile.exists()) {
                    try {
                        errorFile.createNewFile();
                    } catch (IOException e) {
                        if (isLoggingError()) {
                            logError("Can not create new file : " + errorFile.getAbsolutePath(), e);
                        }
                    }
                }
            }
        } else {
            if (isLoggingDebug()) {
                logDebug("file path is null");
            }
        }

        return errorFile;
    }

    /**
     * Takes an alternate name of the file.
     */
    public void archiveFile(final String directoryPath, final File originalFile, String alternateName){
        if(!StringUtils.isBlank(directoryPath) && originalFile!=null){
                final File file = new File(directoryPath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                String path = directoryPath;
                if(!directoryPath.endsWith("\\") &&  !directoryPath.endsWith("/")){
                    path+=File.separatorChar;
                }
                path += alternateName;
                originalFile.renameTo(new File(path));
        }
    }
    /**
     * The Class FileNameFilterImpl.
     */
    class FileNameFilterImpl implements FilenameFilter {

        /** The prefix. */
        private String prefix;

        /**
         * Instantiates a new file name filter impl.
         *
         * @param prefix
         *            the prefix
         */
        FileNameFilterImpl(String prefix) {
            this.prefix = prefix;
        }

        /*
         * (non-Javadoc)
         *
         * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String)
         */
        @Override
        public boolean accept(File dir, String name) {
            return name.startsWith(prefix);
        }

    }
}
